#include <fstream>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <regex>

#include "../source/server.hpp"

//直接定义全局，在启动服务器时只需要初始化一次unordered_map,从而减少了初始化次数提高效率。
std::unordered_map<int,std::string> _statu_msg = 
    {{100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}};

std::unordered_map<std::string,std::string> _mime_msg = 
    {{".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}};

class Util
{
public:
    //该类所提供的都是一些零碎的接口，不需要成员之间有联系，所以都设置成静态，没有this指针
    //字符串分割
    //abc
    //array是一个输入型参数，保存分割后的子串
    //返回值是切割的子串的数量
    static size_t Split(const std::string& src,const std::string& sep,std::vector<std::string>* array)
    {
        size_t offset = 0; // 切割的位置
        //abc,def,,,ghi,
        while(offset < src.size())
        {
            size_t pos = src.find(sep,offset); //从offset位置开始找sep分割字符/串
            if(pos == std::string::npos) //找不到分割字符串，但是得先把最后一个位置的字符串放入array
            {
                if(pos == src.size())   
                    break;
                array->push_back(src.substr(offset));
                return array->size();
            }
            //找到了，分割字符串添加进array，然后offset往后走
            if(offset == pos) //如果找到的是一个空字符串,直接跳过不用添加进array
            {
                offset = pos + sep.size();
                continue;
            }
            array->push_back(src.substr(offset,pos - offset));
            offset = pos + sep.size();
        }
        return array->size();
    }

    //读取文件内容(所有)
    static bool ReadFile(const std::string &filename, std::string *buf) 
    {
        //以二进制形式打开文件
        std::ifstream ifs(filename, std::ios::binary);
        if (ifs.is_open() == false) {
            printf("OPEN %s FILE FAILED!!", filename.c_str());
            return false;
        }
        size_t fsize = 0;
        ifs.seekg(0, ifs.end);//跳转读写位置到末尾
        fsize = ifs.tellg();  //获取当前读写位置相对于起始位置的偏移量，从末尾偏移刚好就是文件大小
        ifs.seekg(0, ifs.beg);//跳转到起始位置

        buf->resize(fsize); //开辟文件大小的空间
        
        ifs.read(&(*buf)[0], fsize);
        //检查文件状态（读取错误，出现异常）
        if (ifs.good() == false) 
        {
            printf("READ %s FILE FAILED!!", filename.c_str());
            ifs.close();
            return false;
        }
        
        ifs.close();
        return true;
    }

    //向文件写入内容
    static bool WriteFile(const std::string& filename,const std::string& data)
    {
        //binary：以二进制模式打开文件trunc：将文件原有内容丢弃
        std::ofstream ofs(filename, std::ofstream::binary | std::ofstream::trunc);
        if(ofs.is_open() == false)
        {
            printf("OPEN %s FILE FAILED!!", filename.c_str());
            return false;
        }

        ofs.write(data.c_str(),data.size());
        if(ofs.good() == false)
        {
            ERROR_LOG("WRITE %s FILE FAILED!", filename.c_str());
            ofs.close();    
            return false;
        }
        ofs.close();
        return true;
    }

    //URL编码
     //URL编码，避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
        //编码格式：将特殊字符的ascii值，转换为两个16进制字符，前缀%   C++ -> C%2B%2B
        //  不编码的特殊字符： RFC3986文档规定 . - _ ~ 字母，数字属于绝对不编码字符
        //RFC3986文档规定，编码格式 %HH 
        //W3C标准中规定，查询字符串中的空格，需要编码为+， 解码则是+转空格
                                                    //url和空格是分开解码的
    static std::string URLEncode(const std::string& url,bool convert_space_to_plus)
    {
        std::string ret;
        for(auto& c : url)
        {
            if(c == '.' || c =='-' || c == '_' || c == '~' || isalnum(c))
                ret += c;
            else if(c == ' ' && convert_space_to_plus == true)
                ret += '+';
            else // 编码格式： %HH
                //snprintf 与 printf比较类似，都是格式化字符串，只不过一个是打印，一个是放到一块空间中
            {
                char tmp[4];
                //%%：一个%，%02X：转换为两位的十六进制数，并在不足两位时用前导零填充
                snprintf(tmp,4,"%%%02X",c);
                ret +=tmp;
            }
        }
        return ret;
    }
    
    //十六进制转整形
    static char HEXTOINT(char c)
    {
        if(c >= '0' && c <='9')
            return c - '0';
        if(c >= 'a' && c <='z')
            return c - 'a' + 10;
        if(c >= 'A' && c <='Z')
            return c - 'A' + 10;
        
        return -1;
    }
    //URL解码
    //遇到了%，则将紧随其后的2个字符，转换为数字，第一个数字左移4位，然后加上第二个数字  + -> 2b  %2b->2 << 4 + 11
    //遇到+，且plus_to_convert_space = true,则+转空格
    static std::string URLDecode(const std::string& url,bool plus_to_convert_space)
    {
        std::string ret;
        for(int i =0;i < url.size();i++)
        {
            if(url[i] == '+' && plus_to_convert_space == true)
            {
                ret += ' ';
            }
            else if(url[i] == '%' && (i+2) < url.size())
            {
                char v1 = HEXTOINT(url[i+1]);
                char v2 = HEXTOINT(url[i+2]);
                char v = (v1 << 4) + v2;
                ret += v;
                i+=2;
            }
            else             
                ret += url[i];
        }
        return ret;
    }

    //响应状态码描述信息的获取
    static std::string StatuDesc(int statu)
    {
        auto it = _statu_msg.find(statu);
        if(it == _statu_msg.end()) //找不到
        {
            return "Unknow";
        }
        return it->second;
    }

    //根据文件后缀名获取mime
    static std::string ExtMime(const std::string& filename)
    {
        // a.b.txt  先获取文件扩展名 
        //find_last_of,从filename的后往前找字符'.';
        size_t pos = filename.find_last_of('.');
        if (pos == std::string::npos) 
        {
            //告知浏览器服务器返回的是一个二进制流，这种情况下，浏览器默认的处理方式是下载文件
            return "application/octet-stream";
        }
        //根据扩展名，获取mime
        std::string ext = filename.substr(pos);
        auto it = _mime_msg.find(ext);
        if (it == _mime_msg.end()) 
        {
            return "application/octet-stream";
        }
        return it->second;
    }

    //判断一个文件是否是目录
    static bool IsDirectory(const std::string &filename)
    {
        struct stat st;
        //stat()是用来描述一个linux系统文件系统中的文件属性的结构
        int ret = stat(filename.c_str(),&st);
        if(ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode); 
    }
    //判断一个文件是否是普通文件
    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        //stat()是用来描述一个linux系统文件系统中的文件属性的结构
        int ret = stat(filename.c_str(),&st);
        if(ret < 0)
        {
            return false;
        }
        return S_ISREG(st.st_mode);
    }

    //判断一个Http资源路径的有效性(只能查找相对根目录以内的资源)
        // /index.html  --- 前边的/叫做相对根目录  映射的是某个服务器上的子目录
        // 想表达的意思就是，客户端只能请求相对根目录中的资源，其他地方的资源都不予理会
        // /../login, 这个路径中的..会让路径的查找跑到相对根目录之外，这是不合理的，不安全的

        //思路：按照"/"进行资源路径的划分
    static bool IsValidPath(const std::string& path)
    {
        std::vector<std::string> subdir; 
        int level = 0;
        Split(path,"/",&subdir);
        
        for(auto &str : subdir)
        {
            if(str == "..") //认为走到相对根目录之外，不合理
            {
                --level;
                if(level < 0)   
                    return false;

            }
            else
                ++level;
        }
        return true;
    }

};

class HttpRequest
{
public:
//将成员变量设置为公有，便于直接访问
    std::string _method;    //请求方法
    std::string _path;      //资源路径
    std::string _version;   //协议版本
    std::string _body;      //请求正文信息
    std::smatch _matches;   //资源路径的正则提取数据
    std::unordered_map<std::string,std::string> _headers; //头部字段
    std::unordered_map<std::string,std::string> _params;  //查询字符串

public:
    HttpRequest()
        :_version("HTTP/1.1")
        {}

    void ReSet()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch match;
        _matches.swap(match);
        _headers.clear();
        _params.clear();
    }

    //插入头部字段
    void SetHeader(const std::string& key,const std::string& val)
    {
        _headers.insert(std::make_pair(key,val));
    }

    //判断是否存在指定头部字段
    bool HasHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return false;
        }
        return true;
    }

    //获取指定头部字段的值
    std::string GetHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return "";
        }
        return it->second;
    }
    
    //插入查询字符串
    void SetParam(const std::string& key,const std::string& val)
    {
        _params.insert(std::make_pair(key,val));
    }

    //判断是否有某个指定的查询字符串
    bool HasParam(std::string& key) const
    {
        auto it = _params.find(key);
        if(it == _params.end())
        {
            return false;
        }
        return true;
    }

    //获取指定的查询字符串
    std::string GetParam(const std::string& key) const
    {
        auto it = _params.find(key);
        if(it == _params.end())
        {
            return "";
        }
        return it->second;
    }

    //获取正文长度
    //头部字段中存在一个字段：Content-Length，先判断是否存在，再获取长度
    size_t ContentLength() const
    {
        bool ret = HasHeader("Content-Length");
        if(ret == false)
            return 0;
        
        std::string Clen = GetHeader("Content-Length");
        return std::stol(Clen);
    }
    //判断是否是短链接（Close是短链接)--keep-alive是长链接
    //只有当头部字段中含有"Connection"字段且对应的值是keep-alive才是长链接，否则都是短链接 
    bool Close() const
    {
        //DEBUG_LOG("[%d]",HasHeader("Connection"));
        //std::cout << "==============================" << std::endl;
        //DEBUG_LOG("[%s]",GetHeader("Connection").c_str());
        //std::cout << "==============================" << std::endl;
        if(HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;

        return true;
    }
};

class HttpResponse
{
public:
    int _statu;         //状态码
    bool _redirect_flag; //重定向标志，默认是false
    std::string _body;  
    std::string _redirect_url; //重定向到的链接
    std::unordered_map<std::string,std::string> _headers; //保存头部字段的信息
public:
    HttpResponse()
        :_redirect_flag(false), _statu(200) 
    {}
    
    HttpResponse(int statu)
        :_redirect_flag(false), _statu(statu) 
    {} 
    void ReSet()
    {
        _statu = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
       //插入头部字段
    void SetHeader(const std::string& key,const std::string& val)
    {
        _headers.insert(std::make_pair(key,val));
    }

    //判断是否存在指定头部字段
    bool HasHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return false;
        }
        return true;
    }

    //获取指定头部字段的值
    std::string GetHeader(const std::string& key) const 
    {
        auto it = _headers.find(key);
        if(it == _headers.end())
        {
            return "";
        }
        return it->second;
    }

    //设置响应正文内容
    void SetContent(const std::string& body,const std::string& type = "text/html")
    {
        _body = body;
        SetHeader("Content-type",type);
    }

    //设置重定向
    void SetRedirect(const std::string& url,int statu = 302)
    {
        _statu = statu;
        _redirect_flag = true;
        _redirect_url = url;
    }   

    //判断是长链接还是短链接
    bool Close() const 
    {
        if(HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }

};
typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
}HttpRecvStatu;

#define MAX_LINE 8192

class HttpContext
{
private:
    int _resp_statu; //响应状态码
    HttpRecvStatu _recv_statu; //当前接收及解析的阶段状态
    HttpRequest _request;       //已经解析得到的请求信息

private:
    std::string GetLine(Buffer* buf)
    {
        //1.获取一行
        std::string line = buf->GetLine();
        if(line.size() == 0) //缓冲区数据不足一行
        {
            //判断特殊情况是否是没有换行符导致一行数据过长
            if(buf->GetReadableSpace() > MAX_LINE) //一行数据太长了，有问题
            {
                _recv_statu = RECV_HTTP_ERROR; 
                _resp_statu = 414; //URL TOO LONG
                return "";
            }
            return "";
        }
        //获取到的一行数据太长了有问题。
        if(line.size() > MAX_LINE)
        {
            _recv_statu = RECV_HTTP_ERROR; 
            _resp_statu = 414; //URL TOO LONG
            return "";
        }

        //在buf->GetLine()函数中读取完一行后已经将读指针后移了。
        return line;
    }    
    
    //接收请求行
    bool RecvHttpLine(Buffer* buf)
    {
        if(_recv_statu != RECV_HTTP_LINE)   
            return false;

        //1.获取一行数据,连带回车换行都获取了，并且获取完后会自动跳过该行
        std::string line = GetLine(buf);
        if(line == "")
            return false;
        //2.解析请求行
        bool ret = ParseHttpLine(line);
        if(ret == false)
            return false;

        //首行处理完毕，进入头部处理阶段
        _recv_statu = RECV_HTTP_HEAD;
        return true;
    }
    
    //解析请求行
    bool ParseHttpLine(std::string& line)
    {
        //1.解析工作
        // HTTP请求行格式 "GET /bitejiuyeke/login?user=xiaoming&pass=123123 HTTP/1.1\r\n"
        std::smatch matches; //存储容器
        //请求方法的匹配： GET HEAD POST PUT DELETE ..
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase); 
        // "."匹配任意非\r\n的单个字符,"*"表示能匹配前面的"."0次或多次
        //很明显，这里就是匹配除了GET之后的所有字符
        bool ret = std::regex_match(line,matches,e);
        if(ret == false)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; // BAD REQUEST
            ERROR_LOG("regex_match error: %s:%d",strerror(errno));
            return false;
        }
        
        //2.将解析结果放入_request中
        //0:GET /bitejiuyeke/login?user=xiaoming&pass=123123 HTTP/1.1 
        //1:GET 
        //2:/bitejiuyeke/login 
        //3:user=xiaoming&pass=123123 
        //4:HTTP/1.1
        _request._method = matches[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        //将方法转化成大写的
        _request._path = matches[2];
        _request._version = matches[4];
        
        std::vector<std::string> query_string_array;
        std::string query_string = matches[3];
        //查询字符串的格式为 key=val&key=val, 先以&进行字符串切割
        //针对各个字符串，以 = 符号进行切割， 得到key 和 val，并对key和val进行解码保存
        Util::Split(query_string,"&",&query_string_array);

        for(auto& str :query_string_array)
        {
            //按'='进行切割
            size_t pos = str.find("=");
            if(pos == std::string::npos)
            {
                //该查询字符串是错的
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400; //BAD REQUEST
                ERROR_LOG("find '=' error");
                return false;
            }
            std::string key = Util::URLDecode(str.substr(0,pos) ,true);
            std::string val = Util::URLDecode(str.substr(pos+1) ,true);

            _request.SetParam(key,val);
        }

        return true;
    }

    //接收请求行头部
    bool RecvHttpHead(Buffer* buf)
    {
        if(_recv_statu != RECV_HTTP_HEAD)
            return false;

        //一行一行取出数据，直到遇到空行为止，说明头部数据获取完了
        //头部格式： key: val\r\nkey: val\r\n
          //1.循环获取一行数据
        while(1)
        {
            std::string line = GetLine(buf);
            if(line == "")
                return false;
            if(line == "\n" || line == "\r\n") //请求行头部获取完了
                break;

            //2.解析请求行头部 
            bool ret = ParseHttpHead(line);
            if(ret == false)
                return false;
        }
        //头部处理完毕，进入正文获取阶段
        _recv_statu = RECV_HTTP_BODY; 
        return true;
    }

    //解析请求行头部
    //头部格式： key: val\r\nkey: val\r\n
    //找": "    
    
    //在对请求头部这行解析时，没有处理\r\n,导致在判断是否是短链接时，
    //"Connection"字段对应的值为："keep-alive\r\n"，导致判断出错
    bool ParseHttpHead(std::string& line)
    {
        if(line.back() == '\n') line.pop_back();
        if(line.back() == '\r') line.pop_back();
        size_t pos = line.find(": ");
        if(pos == std::string::npos)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; //BAD REQUEST
            ERROR_LOG("ParseHttpHead error : %s", line.c_str());
            return false;
        }
        std::string key = line.substr(0,pos);
        std::string val = line.substr(pos+2);

        _request.SetHeader(key,val);
        return true;
    }
    
    bool RecvHttpBody(Buffer* buf)
    {
        if(_recv_statu != RECV_HTTP_BODY)
            return false;
        //1.获取需要的正文长度
        ssize_t content_length = _request.ContentLength();
        //2.获取当前已经接收了多少正文，总需求的 - 已经接收的 = 还需要获取的
        ssize_t real_len = content_length - _request._body.size();
        //3.1缓冲区的数据包含了当前所需要的请求正文，则取出数据
        if(buf->GetReadableSpace() >= real_len)
        {
            _request._body.append(buf->GetReadPos(),real_len);
            buf->MoveReadOffset(real_len);
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        //3.2缓冲区的数据不足，也先取出来， 再等待下次数据就绪
        _request._body.append(buf->GetReadPos(),buf->GetReadableSpace());
        buf->MoveReadOffset(buf->GetReadableSpace());
        //不设置状态码，下次还要接收
        return true;
    }

public:
    HttpContext()
        :_resp_statu(200),_recv_statu(RECV_HTTP_LINE)
    {}
    void ReSet()
    {
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;
        _request.ReSet();
    }
    //返回响应状态
    int RespStatu()
    {
        return _resp_statu;
    }
    //返回接收状态
    HttpRecvStatu RecvStatu()
    {
        return _recv_statu;
    }
    
    HttpRequest& Request()
    {
        return _request;
    }

    void RecvHttpRequest(Buffer* buf) //接收并解析Http请求
    {
        //这里不需要break，在接受完请求行后应立即处理头部
        switch(_recv_statu)
        {
            case RECV_HTTP_LINE : 
                //DEBUG_LOG("RecvHttpLine begin: ");
                RecvHttpLine(buf);
            case RECV_HTTP_HEAD : 
                //DEBUG_LOG("RecvHttpHead begin: ");
                RecvHttpHead(buf);
            case RECV_HTTP_BODY : 
                //DEBUG_LOG("RecvHttpBody begin: ");
                RecvHttpBody(buf);
        }
        return;
    }
};

#define DEFAULT_TIMEOUT 10
class HttpServer
{
private:
    //这里的string并不是保存请求的资源路径，因为路径是唯一的，而是保存的正则表达式，这样保存的Get方法的
    //路由表中就能多个路径映射一个回调处理函数了
    using Handler = std::function<void(const HttpRequest& ,HttpResponse*)> ;
    using Handlers = std::vector<std::pair<std::regex,Handler>>;   //unordered_map并不太支持正则表达式
    Handlers _get_route;
    Handlers _put_route;
    Handlers _post_route;
    Handlers _delete_route;

    std::string _basedir = "./wwwroot/"; //静态资源根目录
    TcpServer _server;

private:
    //子子模块
    void ErrorHandler(const HttpRequest& req,HttpResponse* rsp)
    {
        //1.组织一个错误展示页面
        std::string body;
        body += "<html>";

        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        
        body +="<body>";
        body +="<h1>";
        body += std::to_string(rsp->_statu);
        body +=":";
        body +=Util::StatuDesc(rsp->_statu);
        body +="</h1>";
        body +="</body>";
        
        body += "</html>";
        //2.将页面数据当做响应正文添加到rsp中
        rsp->SetContent(body,"text/html");
    }
    
private:
    //将HttpResponse的要素按照Http协议格式进行组织发送
    void WriteResponse(const PtrConnection& conn,const HttpRequest& req, HttpResponse& rsp) 
    {
        //1.先完善头部字段
        if(req.Close() == true) //短链接
            rsp.SetHeader("Connection","close");
        else 
            rsp.SetHeader("Connection","keep-alive");

        if(rsp._body.empty() == false && rsp.HasHeader("Content-Length") == false)
            rsp.SetHeader("Content-Length",std::to_string(rsp._body.size()));

        if(rsp._body.empty() == false && rsp.HasHeader("Content-Type") == false)
            rsp.SetHeader("Content-Type","application/octet-stream");

        if(rsp._redirect_flag == true) // 重定向到的链接
            rsp.SetHeader("Location",rsp._redirect_url);
        //2.将rsp的要素，按照http协议格式进行组织
        //组织头部
        std::stringstream rsp_str;
        rsp_str << req._version <<" "<<std::to_string(rsp._statu)<<" "<< Util::StatuDesc(rsp._statu) << "\r\n";
        for(auto &it : rsp._headers)
        {
            rsp_str << it.first << ":" << it.second << "\r\n";
        }
        //组织空行
        rsp_str << "\r\n";
        //组织正文
        rsp_str << rsp._body;
        //3.发送数据
        conn->Send(rsp_str.str().c_str(),rsp_str.str().size());
        //printf("Send message to client success\n");
    }
    //静态资源的请求处理
    //读取文件的内容放入到rsp._body中，再设置Mime
    void FileHandler(const HttpRequest& req, HttpResponse* rsp)
    {
        std::string req_path = _basedir + req._path;
        bool ret = Util::ReadFile(req_path, &rsp->_body);
        if(ret == false)
            return ;
        
        //设置Mime
        std::string mime = Util::ExtMime(req_path);
        rsp->SetHeader("Content-Type",mime);
        return ;
    }
    //判断是否是静态资源
    bool IsFileHandler(const HttpRequest& req)
    {
        //std::cout <<"=================" << req._method << " " << req._path << std::endl;
        //1.必须设置了静态资源根目录
        if(_basedir.empty())
            return false;
        //2.请求方法必须是Get/Head方法
        if(req._method != "GET" && req._method != "HEAD"){
            //std::cout << "   ====================================req._method != GET || req._method != HEAD "  << std::endl;
            return false;
        }
        //3.请求的资源路径必须是一个合法路径
        if(Util::IsValidPath(req._path) == false){
            //std::cout << "   ==================================== Util::IsValidPath(req._path) == false"  << std::endl;
            return false;
        }
        //4.请求的资源必须存在,并且是一个普通文件
        //特殊情况：目录：/,/image,这种情况默认在后面追加 index.html
        std::string req_path = _basedir + req._path; //避免直接修改请求的资源路径，这里用临时对象存储
        //不能忘记将请求路径转化为实际存在的路径，也就是要+_basedir
        //在执行这个代码之前就退出这个函数了
        //std::cout << "   ==================================== " <<  req_path << std::endl;
        if(req._path.back() == '/') //是根目录
        {
            req_path += "index.html"; //此时实际访问的路径是：_basedir/index.html
        }
        // ./wwwroot/main.cpp
        if(Util::IsRegular(req_path) == false) 
        {
            return false;
        }

        return true;
    }

    //regex函数对req修改了，不能加const
    void DispatcherRoute(HttpRequest& req, HttpResponse* rsp,Handlers& handlers) //功能性请求的分类处理
    {   
        for(auto &handler : handlers)
        {
            const std::regex& re = handler.first;
            const Handler& functor = handler.second;
            bool ret = std::regex_match(req._path,req._matches,re);
            if(ret == false)
                continue;

            return functor(req,rsp);
        }
        rsp->_statu = 404;//NO FOUND
    }   

     //分辨是静态资源请求还是功能性请求
    void Route(HttpRequest& req, HttpResponse* rsp)     
    {
        //1.先对请求资源路径分辨是静态资源路径还是功能性请求路径
        //如果是静态资源路径，则进行静态资源的处理
        //如果是功能性请求路径，则查询几个路由表查询是否有处理函数
        //如果都不是，则返回405
        bool ret = IsFileHandler(req);
        //printf("IsFileHandler !\n");
        if(ret == true)
        {
            FileHandler(req,rsp);
            return;
        }

        if(req._method == "GET" || req._method == "HEAD")
        {
            DispatcherRoute(req,rsp,_get_route);
        }
        else if(req._method == "POST" )
        {
            DispatcherRoute(req,rsp,_post_route);
        }
        else if(req._method == "PUT")
        {
            DispatcherRoute(req,rsp,_put_route);
        }
        else if(req._method == "DELETE")
        {
            DispatcherRoute(req,rsp,_delete_route);
        }
        //都不是，状态码设置    
        else
            rsp->_statu = 405; //Method Not Allowed
        return;
    }
    
    //给连接设置上下文
    void OnConnected(const PtrConnection& conn) 
    {
        conn->SetContext(HttpContext());
        DEBUG_LOG("NEW CONNECTION : %p",this);
    }
    
    //对缓冲区数据解析+处理
    void OnMessage(const PtrConnection& conn,Buffer* buf) 
    {
        //只要该链接的缓冲区中有数据就持续处理
        while(buf->GetReadableSpace() > 0)
        {
            //1.获取连接的上下文
            HttpContext* context = conn->GetContext()->get<HttpContext>();
            //2.通过上下文对缓冲区数据进行解析，得到HttpRequest对象
            //2.1如果解析失败，则组织错误信息页面的响应返还给客户端
            //2.2如果解析成功，才正常执行下面的操作
            //在这里打印一下接收到的请求看看
            context->RecvHttpRequest(buf);
            //DEBUG_LOG("%s",buf->GetReadPos());
            //printf("RecvHttpRequest success\n");

            HttpRequest &req = context->Request();//不能使用临时对象接收引用对象，容易出问题
            HttpResponse rsp(context->RespStatu());
            //printf("context->RespStatu：%d\n",context->RespStatu());
            if(context->RespStatu() >= 400) 
            {
                //printf("return error message to client\n");
                //解析错误了，组织错误页面响应返回给客户端，把缓冲区数据清空
                ErrorHandler(req,&rsp);
                //printf("ErrorHandler success\n");
                WriteResponse(conn,req,rsp); //通过conn链接将组织好的http响应发送给客户端
                //DEBUG_LOG("%s",rsp._body.c_str());
                printf("1026----------------------------------\n");

                //出错了会取出缓冲区数据解析然后将错误页面响应发送给客户端（未清空缓冲区的前提下）
                //printf("WriteResponse error message success\n");

                //错误处理后，必须重置上下文，否则接收状态一直是RECV_HTTP_ERROR，就导致无法处理缓冲区的数据，陷入死循环
                context->ReSet();
                buf->MoveReadOffset(buf->GetReadableSpace());//出错了就把缓冲区数据清空

                conn->Shutdown(); //shutdown内部会判断缓冲区数据是否处理完成了，如果没有，则继续调用回调继续处理
                return ;
            }

            //std::cout << "context->RecvStatu: " << context->RecvStatu() << std::endl;
            if(context->RecvStatu() != RECV_HTTP_OVER)
            {
                //当前请求还没接收完整，退出等待下一次请求就绪
                return;
            }

            //3.请求路由 + 业务处理
            Route(req,&rsp);
            //printf("Route success\n");
            
            //4.对HttpResponse进行请求发送
            WriteResponse(conn,req,rsp); //通过conn链接将组织好的http响应发送给客户端
            //DEBUG_LOG("%s",rsp._body.c_str());
            //printf("1053----------------------------------\n");
            //printf("WriteResponse success\n");

            //5.重置上下文——只有重置上下文后，下次数据处理才不会受到本次的影响
            context->ReSet();
            //printf("context->ReSet success\n");

            //6.根据长短链接判断是否要关闭连接还是继续处理
            //std::cout <<rsp.Close() << std::endl;
            if(rsp.Close() == true) //是短链接直接关闭
                conn->Shutdown();
        }
        return ;    
    }

public:
    HttpServer(int port,int timeout = DEFAULT_TIMEOUT)
        :_server(port)
    {
        _server.EnableInactiveRelease(timeout); 
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected,this,std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage,this,std::placeholders::_1,std::placeholders::_2));
    }
    void SetBaseDir(const std::string& path) //设置静态资源根目录
    {
        assert(Util::IsDirectory(path) == true);
        _basedir = path;
    }
    void AddGetRoute(const std::string& pattern,const Handler& handler) //添加<Get正则表达式：处理方法>
    {
        //不能忽略大小写，无需std::regex(pattern,std::regex::icase);
        _get_route.push_back(std::make_pair(std::regex(pattern),handler));
    }
    void AddPostRoute(const std::string& pattern,const Handler& handler)
    {
        _post_route.push_back(std::make_pair(std::regex(pattern),handler));
    }
    void AddPutRoute(const std::string& pattern,const Handler& handler)
    {
        _put_route.push_back(std::make_pair(std::regex(pattern),handler));
    }
    void AddDeleteRoute(const std::string& pattern,const Handler& handler)
    {
        _delete_route.push_back(std::make_pair(std::regex(pattern),handler));
    }
    void SetThreadCount(int count)
    {
        _server.SetThreadCount(count);
    }
    void Listen()
    {
        _server.Start();
    }
};